package com.echo.im.engin.config;

import com.echo.im.common.contant.MQConstants;
import com.echo.im.engin.mq.PushMessageReceiver;
import com.echo.im.engin.netty.IMServerGroup;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.MessageListenerContainer;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

/**
 * @description: im-engin-engin 中 是一对一绑定的这个队列
 * @author echo
 */
@Configuration
//等待im-server启动好了之后获取serverId之后开始绑定队列
@DependsOn("IMServerGroup")
public class RabbitConfig{

    @Bean
    DirectExchange pushDirect() {
        return ExchangeBuilder
                .directExchange(MQConstants.ECHO_EXCHANGE)
                .durable(true)
                .build();
    }

    @Bean
    public Queue pushMessageQueue() {
        return new Queue(join(MQConstants.PUSH_MESSAGE_QUEUE, IMServerGroup.serverId));
    }

    @Bean
    Binding privatePushBinding(DirectExchange pushDirect, Queue pushMessageQueue) {
        return BindingBuilder
                .bind(pushMessageQueue)
                .to(pushDirect)
                .with(join(MQConstants.PUSH_MESSAGE_TOPIC, IMServerGroup.serverId));
    }

    private String join(String str, Long serverId) {
        return str + "." + serverId.toString();
    }

    @Bean
    public MessageListenerContainer messageListenerContainer(ConnectionFactory connectionFactory, Queue pushMessageQueue, PushMessageReceiver pushMessageReceiver) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueues(pushMessageQueue);

        container.setMessageListener(pushMessageReceiver);

        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        container.setPrefetchCount(10);
        container.setBatchSize(10);
        container.setConsumerBatchEnabled(true);
        container.setMaxConcurrentConsumers(4);
        container.setConcurrentConsumers(2);
        return container;
    }

}